<?php

namespace App\Models\Finance;

use App\Observers\Finance\MarketPriceObserver;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class MarketPrice extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'yida_market_prices';


    protected $fillable = [
		'market',
		'coin',
		'currency',
		'last',
		'buy',
        'high',
		'sell',
        'rate'
	];

    public static function boot()
    {
        parent::boot();
        static::created(function ($marketPrices){
            $adminId = isset(Admin::user()->id) ? Admin::user()->id : 0;
            $data['admin_id'] = $adminId;
            $data['ip'] = request()->ip();
            $data['url'] = request()->url();
            $data['message'] = ['before_insert'=>$marketPrices->toArray()];
            Log::channel("LaravelInsert")->error("添加操作",[
                'function'=>__CLASS__.'->'.__FUNCTION__.'()',
                'code_line'=>__LINE__,
                'action'=>"insert",
                'message'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'title' => "添加操作",
                'table' => "yida_market_prices"
            ]);
        });
        static::updated(function ($marketPrices){
            $adminId = isset(Admin::user()->id) ? Admin::user()->id : 0;
            $data['admin_id'] = $adminId;
            $data['ip'] = request()->ip();
            $data['url'] = request()->url();
            $data['message'] = ['before_update'=>$marketPrices->toArray()];
            Log::channel("LaravelUpdate")->error("更新操作",[
                'function'=>__CLASS__.'->'.__FUNCTION__.'()',
                'code_line'=>__LINE__,
                'action'=>"update",
                'message'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'title' => "更新操作",
                'table' => "yida_market_prices"
            ]);
        });
        static::deleted(function ($marketPrices){

            $adminId = isset(Admin::user()->id) ? Admin::user()->id : 0;
            $data['admin_id'] = $adminId;
            $data['ip'] = request()->ip();
            $data['url'] = request()->url();
            $data['message'] = ['before_delete'=>$marketPrices->toArray()];
            Log::channel("LaravelDelete")->error("删除操作",[
                'function'=>__CLASS__.'->'.__FUNCTION__.'()',
                'code_line'=>__LINE__,
                'action'=>"delete",
                'message'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'title' => "删除操作",
                'table' => "yida_market_prices"
            ]);
        });
    }

    public function getRateAttribute()
    {
        return bcmul($this->attributes['rate'],1,2);
    }

}
